package com.wukang.photovoltaicinspectionpictures.logger

import android.os.Environment
import com.tencent.mars.xlog.Log
import com.tencent.mars.xlog.Xlog
import java.io.File

/**
 * 日志工具管理类
 * @author wukang
 */
internal object XLogManager {
    fun init(isDEBUG: Boolean, cacheDays: Int) {
        init(isDEBUG, Xlog(), cacheDays)
    }

    fun init(isDEBUG: Boolean, xlog: Xlog?, cacheDays: Int) {
        System.loadLibrary("c++_shared")
        System.loadLibrary("marsxlog")
        val logPathFile = getLogPathFile() //获取xLog
        val cachePath = getLogCachePathFile()
        RogFileUtils.makeDir(logPathFile)
        RogFileUtils.makeDir(cachePath)
        RogFileUtils.makeDir(getZipPathFile())
        Log.setLogImp(xlog)
        Log.setConsoleLogOpen(isDEBUG)
        Log.appenderOpen(
            Xlog.LEVEL_ALL,
            Xlog.AppednerModeAsync,
            cachePath?.absolutePath,
            logPathFile?.absolutePath,
            RogConstants.X_LOG_FILE_NAME,
            cacheDays
        )
    }

    fun readMsg(callback: (File?) -> Unit) {
        callback(syncGetLogZipFile())
    }

    fun upLoadClear() {
        syncDeleteLogFile()
    }

    private fun syncGetLogZipFile(): File? {
        Log.appenderFlushSync(true)
        try {
            val logFile = getLogPathFile() ?: return null
            if (logFile.exists() && logFile.length() > 0 && !logFile.listFiles().isNullOrEmpty()) {
                RogFileUtils.clearIfNeed(logFile, RogConstants.UPLOAD_DATA_FILE_MAX_LENGTH)
                return getZipFile().also {
                    RogFileUtils.deleteFile(it)
                    RogFileUtils.makeFile(it)
                    RogFileUtils.ZipFolder(logFile, it)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    private fun syncDeleteLogFile() {
        RogFileUtils.deleteFileChild(getLogPathFile())
        RogFileUtils.deleteFileChild(getZipPathFile())
        RogFileUtils.deleteFileChild(getLogCachePathFile())
    }

    private fun getLogPathFile(): File? {
        val document = Rog.mApplication?.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) ?: return null
        return File(document.absolutePath, RogConstants.X_LOG_PATH_SDCARD_DIR)
    }

    private fun getLogCachePathFile(): File? {
        val document = Rog.mApplication?.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) ?: return null
        return File(document.absolutePath, RogConstants.X_LOG_CACHE_PATH_SDCARD_DIR)
    }

    private fun getZipPathFile(): File? {
        val document = Rog.mApplication?.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) ?: return null
        return File(document.toString(), RogConstants.X_LOG_PATH_ZIP)
    }

    private fun getZipFile(): File {
        return File(getZipPathFile(), RogConstants.X_LOG_ZIP_FILE_NAME)
    }
}